<?php
namespace App\Admin\Controllers\Traits\WxSettingTraits;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\SiteUtils;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Widgets\Tooltip;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

trait formOssTrait{
    public function oss(Content $content, Request $request)
    {
        if ($request->isMethod('post')) {
            $data = $request->post();
            if(!_empty_(_array_key($data, 'bucket', ''))){
                // 使用 preg_match 来匹配
                if (preg_match('/.*-\d{10}$/', trim($data['bucket']))) {
                    return $this->response()->error('存储空间名称 Bucket配置错误，请看红色注意事项');
                }
            }
            SiteUtils::forget_config_data();

            if ($data['ossType'] == 'cosv5') {
                $configData = [
                    'bucket' => $data['bucket'] ?? '',
                    'region' => $data['region'] ?? '',
                    'appId' => $data['appId'] ?? '',
                    'secretId' => $data['secretId'] ?? '',
                    'secretKey' => $data['secretKey'] ?? '',
                    'domain' => rtrim(_array_key($data, 'domain', ''), '/')
                ];
                Settings::set('cosv5', $configData, true);
            }
            Settings::set('ossType', 'cosv5', true);
            Settings::set('image_unused_keep_days', $data['image_unused_keep_days'], true);
            Settings::set('chat_expire_days', $data['chat_expire_days'], true);
            _update_env([
                "COSV5_APP_ID" => $data['appId'] ?? '',
                "COSV5_SECRET_ID" => $data['secretId'] ?? '',
                "COSV5_SECRET_KEY" => $data['secretKey'] ?? '',
                "COSV5_BUCKET" => $data['bucket'] ?? '',
                "COSV5_REGION" => $data['region'] ?? '',
                "COSV5_CDN" => str_replace(['https://', 'http://'], '', $data['domain'] ?? ''),
            ], ['COSV5_TOKEN', 'COSV5_TIMEOUT', 'COSV5_CONNECT_TIMEOUT', 'COSV5_SCHEME', 'COSV5_READ_FROM_CDN', 'COSV5_CDN_KEY', 'COSV5_ENCRYPT']);

            $__global_config_version__ = Settings::get('__global_config_version__', 1) + 1;
            Settings::set('__global_config_version__', $__global_config_version__);
            GatewayUtils::success('all', 13, [ 'version' => $__global_config_version__, 'file' => basename(__FILE__) ]);
            return $this->response()->success('保存成功！')->refresh();
        }
        $form = new Form();
        $form->html(function () {
            return '';
        }, '<b>一、存储配置</b>');
        $form->html(function () {
            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">这里解释一下为什么只能配置腾讯云cos，因为系统越来越复杂，涉及到图片处理，视频截屏，图片清理等等功能，另外经过对比腾讯云比七牛啥的都便宜，所以只适配腾讯云cos，不会安排其他云对象存储或者本地</div>';
        }, '');
        $form->radio('ossType')->help('点击查看<a href="https://doc.minisns.cn/doc/62/" target="_blank">配置教程</a>')
            ->when('cosv5', function (Form $form) {
                $cosv5 = Settings::get('cosv5', []);
                $form->text('bucket', '存储空间名称 Bucket')->help('<b style="color:red;">注意</b>：这里不要填-appid，点击<a href="https://img.mini.minisns.cn/images/cos_tip.jpg" target="_blank">查看教程</a>')->default($cosv5['bucket'] ?? '');
                $form->text('region', '所属地域 Region')->default($cosv5['region'] ?? '');
                $form->text('appId', 'AppId')->default($cosv5['appId'] ?? '');
                $form->text('secretId', 'SecretId')->help('<a href="https://img.mini.minisns.cn/images/appsecret.png" target="_blank">查看说明</a>')->default($cosv5['secretId'] ?? '');
                $form->password('secretKey', 'SecretKey')->default($cosv5['secretKey'] ?? '');
                $form->url('domain', 'Domain')->help('请补全http:// 或 https://，例如：http://img.minisns.cn')->default($cosv5['domain'] ?? '');
            })
            ->options([
                'cosv5' => '腾讯云cos',
            ])
            ->default(Settings::get('ossType', 'cosv5'));
        $form->divider();
        $form->html(function () {
            return '';
        }, '<b>二、策略配置</b>');
        $form->html(function () {
            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">两种类型的未被引用附件: <br>1、用户上传图片后，没有后续动作，比如发布笔记，发表评论，更新资料，提交反馈，提交举报等。<br>2、笔记，评论等被主动删除后，图片也会成为未被引用</div>';
        }, '');
        $res3 = __system__paycode__tip__(3);
        Tooltip::make('.mini_global_admin_open_not_support_tip')
            ->bottom()
            ->title($res3['tip']);
        $form->number('image_unused_keep_days', '附件未被引用几天后清理')->help($res3['text'])->default(Settings::get('image_unused_keep_days', 10));
        $form->number('chat_expire_days', '聊天记录过期时间(天)')->help($res3['text'].'默认三个月，则程序会自动删除三个月之前的聊天记录，并清理掉附件')->default(Settings::get('chat_expire_days', 90));
        $form->divider();
        $form->html(function () {
            return '<span style="color: red;font-weight: bold;">以下若需要文件上传到服务器验证，统一上传到网站的public目录</span>';
        }, '');

        $form->html(function () {
            return '';
        }, '<b>三、微信小程序域名白名单</b>');
        $form->html(function () {
            return '';
        }, '<a href="https://img.mini.minisns.cn/images/wechat_domain_position.jpg" target="_blank">配置位置</a>');

        $cosv5 = Settings::get('cosv5', []);
        $domains = env('APP_URL').'<br/>
'.$cosv5['domain'].'<br/>'.'https://'.$cosv5['bucket'].'-'.$cosv5['appId'].'.cos.'.$cosv5['region'].'.myqcloud.com'.($cosv5['domain'] == 'https://img.mini.minisns.cn' ? '' : '<br/>https://img.mini.minisns.cn').'<br/>https://thirdwx.qlogo.cn<br/>https://open.weixin.qq.com<br/>';
        $form->html(function () use ($domains){
            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">'.$domains.'</div>';
        }, 'request合法域名');

        $form->html(function () use ($domains) {
            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">wss://'.get_mini_domain().'</div>';
        }, 'socket合法域名');

        $form->html(function ()  use ($domains){
            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">'.$domains.'</div>';
        }, 'uploadFile合法域名');

        $form->html(function ()  use ($domains){
            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">'.$domains.'</div>';
        }, 'downloadFile合法域名');

        $form->html(function ()  use ($domains){
            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">'.str_replace('https://', 'udp://', $domains).'</div>';
        }, 'udp合法域名');

        $form->html(function ()  use ($domains){
            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">'.str_replace('https://', 'tcp://', $domains).'</div>';
        }, 'tcp合法域名');

        $form->html(function () {
            return '';
        }, '<b>四、微信小程序业务域名</b>');
        $form->html(function ()  use ($domains){
            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">'.env('APP_URL').'<br/>'.Settings::get('app_h5_home', '').'</div>';
        }, '业务域名');
        $form->html(function () {
            return '';
        }, '<b>五、公众号后台配置</b>');
        $form->html(function () {
            return '';
        }, '<a href="https://img.mini.minisns.cn/images/mp_back_seting1.png" target="_blank">配置位置</a>');
        $form->html(function ()  use ($domains){
            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">'.env('APP_URL').'<br/>'.Settings::get('app_h5_home', '').'</div>';
        }, '业务域名');
        $form->html(function ()  use ($domains){
            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">'.env('APP_URL').'<br/>'.Settings::get('app_h5_home', '').'</div>';
        }, 'JS接口安全域名');
        $form->html(function ()  use ($domains){
            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">'.env('APP_URL').'</div>';
        }, '网页授权域名');
        $form->html(function () {
            return '';
        }, '<a href="https://img.mini.minisns.cn/images/mp_back_seting2.png" target="_blank">配置位置</a>');
        $form->html(function ()  use ($domains){
            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">自己的服务器ip</div>';
        }, 'IP白名单');
        return $content->title('上传设置')
            ->body(
                <<<HTML
<div class="card">{$form->render()}</div>
HTML
            );
    }
}
